﻿using JNPF.Common.Core.Manager;
using JNPF.Common.Core.Security;
using JNPF.Common.Enum;
using JNPF.Common.Extension;
using JNPF.Common.Filter;
using JNPF.Common.Security;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.FriendlyException;
using JNPF.Website.Entitys.Dto.WebsiteNews;
using JNPF.Website.Entitys;
using JNPF.Website.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace JNPF.Website;

/// <summary>
/// 业务实现：新闻管理.
/// </summary>
[ApiDescriptionSettings(Tag = "Website", Name = "WebsiteNews", Order = 200)]
[Route("api/Website/[controller]")]
public class WebsiteNewsService : IWebsiteNewsService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<WebsiteNewsEntity> _repository;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="WebsiteNewsService"/>类型的新实例.
    /// </summary>
    public WebsiteNewsService(
        ISqlSugarRepository<WebsiteNewsEntity> websiteNewsRepository,
        ISqlSugarClient context,
        IUserManager userManager)
    {
        _repository = websiteNewsRepository;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取新闻管理.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<WebsiteNewsInfoOutput>();
    }

    /// <summary>
    /// 获取新闻管理列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] WebsiteNewsListQueryInput input)
    {
        var data = await _repository.Context.Queryable<WebsiteNewsEntity>()
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.categoryId), it => it.CategoryId.Equals(input.categoryId))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it =>
                it.Name.Contains(input.keyword)
                || it.CategoryId.Contains(input.keyword)
                )
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.Id)
            .Select(it => new WebsiteNewsListOutput
            {
                id = it.Id,
                name = it.Name,
                sortCode = it.SortCode,
                publishTime = it.PublishTime,
                isOnHome = it.IsOnHome,
                categoryId = it.CategoryId,
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<WebsiteNewsListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建新闻管理.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] WebsiteNewsCrInput input)
    {
        var entity = input.Adapt<WebsiteNewsEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新新闻管理.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] WebsiteNewsUpInput input)
    {
        var entity = input.Adapt<WebsiteNewsEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除新闻管理.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Deleteable<WebsiteNewsEntity>().Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
    }
}